/****************************************************************************
**
** Copyright (C) 2009 Alexander Solis.
**
** This file is part of Alejandria
** Alejandria is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Alejandria is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Alejandria.  If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/

#include "library.h"

#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlField>
#include <QSqlError>
#include <QMessageBox>
#include <QDir>

Library::Library()
{
	model = NULL;
}
Library::~Library()
{
	delete model;
    delete proxyModel;
}

bool Library::connectToDB()
{
	QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
	db.setDatabaseName(QDir::homePath() + "/Alejandria_Library.db");
    if (!db.open()) {
    	QMessageBox::critical(0, QString("Database Error"),
          	QString(db.lastError().text() + "\n\n"
                     "Click Ok to exit."), QMessageBox::Ok);
        return false;
    }
	else {
		createDBStructure();
		createModelStructure(&db);
		return true;
	}
}

QAbstractItemModel * Library::getSqlTableModel()
{
	return proxyModel;
}

bool Library::insertData (QString id, QString title, QString author, QString category, QString status, QString own, int rating, bool loaned, QString comments)
{
	QSqlField f_id("id", QVariant::String);
	f_id.setValue(id);

	QSqlField f_title("title", QVariant::String);
	f_title.setValue(title);
	
	QSqlField f_author("author", QVariant::String);	
	f_author.setValue(author);
	
	QSqlField f_category("category", QVariant::String);
	f_category.setValue(category);
	
	QSqlField f_status("status", QVariant::String);
	f_status.setValue(status);
	
	QSqlField f_own("own", QVariant::String);
	f_own.setValue(own);
	
	QSqlField f_rating("rating", QVariant::Bool);
	f_rating.setValue(rating);
	
	QSqlField f_loaned("loaned", QVariant::String);	
	f_loaned.setValue(loaned);	
	
	QSqlField f_comments("comments", QVariant::String);
	f_comments.setValue(comments);	
	
	// Creates a record with the information received
	QSqlRecord newRecord;
	newRecord.append(f_id);
	newRecord.append(f_title);
	newRecord.append(f_author);
	newRecord.append(f_category);
	newRecord.append(f_status);
	newRecord.append(f_own);
	newRecord.append(f_rating);
	newRecord.append(f_loaned);
	newRecord.append(f_comments);

    if (isIdAvailable(id))
   	    return 	model->insertRecord(model->rowCount(), newRecord);
    else
        return false;

/*	QSqlQuery query;
    QString insert_query = QString("insert into books "
        "values('%1', '%2', '%3', '%4', '%5', '%6', %7, %8, '%9')").arg(id).arg(title).arg(author).arg(category).arg(status).arg(own).arg(rating).arg(loaned).arg(comments);
    bool result = query.exec(insert_query);

    model->select();

    return result;*/
}

bool Library::isIdAvailable(const QString &id)
{
    //QSqlTableModel *artistModel = model->relationModel(2);
    bool flag = true;
    int row = 0;

    while (row < model->rowCount()) {
        QSqlRecord record = model->record(row);
        if (record.value("id") == id) {
            flag = false;
            break;
        }
        else {
            row++;
        }
    }
    return flag;
}

bool Library::deleteData(int rowToRemove)
{   
	// TODO: allow the user to select several rows to be deleted
	return model->removeRows(rowToRemove, 1);
}

void Library::filter(const QString &filterCriteria)
{
    proxyModel->setFilterKeyColumn(Category);

    if (filterCriteria != "Show All")
        proxyModel->setFilterFixedString(filterCriteria);
    else
        proxyModel->setFilterFixedString(QString(""));       
}

void Library::search(const QString &searchCriteria)
{
    proxyModel->setFilterKeyColumn(-1);
    proxyModel->setFilterFixedString(searchCriteria);
}

void Library::createDBStructure()
{
	QSqlQuery query;
	query.exec("create table books (id varchar(13) primary key, "
		"title varchar(100), author varchar(50), category varchar(100), "
		"status varchar(8), own varchar(3), rating int, loaned boolfield, comments varchar(100), image varchar(300))");
	/*query.exec("insert into books values ('968-5962-51-0', 'El fin de la eternidad', 'Issac Asimov', '', 'Read', 'Yes', 1, '', 'My Comment for this book')");
	query.exec("insert into books values ('968-5962-51-2', 'El fin de la eternidad', 'Issac Asimov', '', 'Read', 'Yes', 1, '', 'My Comment for this book')");*/
}

void Library::createModelStructure(QSqlDatabase *db)
{
	model = new QSqlTableModel(this, *db);
 	model->setTable("books");
	model->setEditStrategy(QSqlTableModel::OnFieldChange);
	model->select();
    model->setHeaderData(Id,       Qt::Horizontal, QObject::tr("ID"));
	model->setHeaderData(Title,    Qt::Horizontal, QObject::tr("Title"));
	model->setHeaderData(Author,   Qt::Horizontal, QObject::tr("Author"));
	model->setHeaderData(Category, Qt::Horizontal, QObject::tr("Category"));	
	model->setHeaderData(Status,   Qt::Horizontal, QObject::tr("Status"));
	model->setHeaderData(Own,      Qt::Horizontal, QObject::tr("Own"));
	model->setHeaderData(Rating,   Qt::Horizontal, QObject::tr("Rating"));
	model->setHeaderData(Loaned,   Qt::Horizontal, QObject::tr("Loaned"));
	model->setHeaderData(Comments, Qt::Horizontal, QObject::tr("Comments"));

    proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel(model);
    proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
}